import React, { useEffect, useRef, useState, useCallback } from 'react'
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "./index"
const formatMsg = () => {
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const friendMsgLis = useQuery(schemaName.FriendMsgLis, friendMsg => {
        return friendMsg.filtered(`UserId == ${userInfo.Id}`)
    })
    const [msgList, setMsgList] = useState()
    const getMsgList = () => {
        const flist = []
        const glist = []
        const friendList = realm.objects(schemaName.FriendList).filtered(`UserId == ${userInfo.Id}`)
        const groupList = realm.objects(schemaName.GroupList).filtered(`UserId == ${userInfo.Id}`)
        friendList.forEach((item, index) => {
            let MsgLis = realm.objects(schemaName.FriendMsgLis).filtered(`F == ${item.F} and  UserId == ${userInfo.Id}`)
            if (MsgLis.length > 0) {
                let UnreadMsgLis = MsgLis.filtered(`Unread == 1`)
                flist.push({ ...item, ...MsgLis[MsgLis.length - 1], Unread: UnreadMsgLis.length })
            } else {
                flist.push({ ...item, T: 0 })
            }
        })
        groupList.forEach(item => {
            let GroupList = realm.objects(schemaName.GroupMsgLis).filtered(`G == ${item.G} and  UserId == ${userInfo.Id}`)
            if (GroupList.length > 0) {
                let UnreadGroupList = GroupList.filtered(`Unread == 1`)
                glist.push({ ...GroupList[GroupList.length - 1], ...item, Unread: UnreadGroupList.length })
            } else {
                glist.push({ ...item, T: 0 })
            }
        })
        setList(flist.concat(glist).sort((a, b) => b.T - a.T))
    }
    return {
        msgList,
        getMsgList
    }
}
export default formatMsg